<template>
  <NavBar
    :leftArrow="true"
    :title="title"
    @onClickLeft="goBack" />

  <div class="publish-page">
    <div class="upload-container">
      <van-uploader
        accept="image"
        :file-list="fileList"
        max-count="1"
        image-fit="aspectFit"
        :after-read="afterRead"
        @delete="deleteFile" />
    </div>

    <!-- 帖子表单 -->
    <div v-if="pageType === 'community'">
      <uni-forms
        ref="form"
        :rules="rules"
        :modelValue="formData">
        <uni-forms-item
          label="标题"
          required
          name="title">
          <uni-easyinput
            v-model="formData.title"
            placeholder="请输入标题" />
        </uni-forms-item>
        <uni-forms-item
          label="内容"
          name="content">
          <uni-easyinput
            type="textarea"
            :autoHeight="true"
            maxlength="200"
            v-model="formData.content"
            placeholder="请输入内容" />
        </uni-forms-item>
      </uni-forms>
    </div>

    <!-- 植物表单 -->
    <div v-if="pageType === 'knowledge' || pageType === 'record'">
      <uni-forms
        ref="form"
        :rules="plantRules"
        :modelValue="plantData">
        <uni-forms-item
          label="名称"
          required
          name="name">
          <uni-easyinput
            v-model="plantData.name"
            placeholder="请输入植物名称" />
        </uni-forms-item>
        <uni-forms-item
          label="学名"
          required
          name="scientificName">
          <uni-easyinput
            v-model="plantData.scientificName"
            placeholder="请输入学名" />
        </uni-forms-item>
        <uni-forms-item
          label="概览"
          required
          name="overview">
          <uni-easyinput
            type="textarea"
            :autoHeight="true"
            maxlength="200"
            v-model="plantData.overview"
            placeholder="请输入概览" />
        </uni-forms-item>
        <uni-forms-item
          label="用途"
          name="usage">
          <uni-easyinput
            type="textarea"
            :autoHeight="true"
            maxlength="200"
            v-model="plantData.usage"
            placeholder="请输入用途" />
        </uni-forms-item>
        <uni-forms-item
          label="状态"
          name="state">
          <uni-easyinput
            v-model="plantData.state"
            placeholder="请输入状态" />
        </uni-forms-item>
        <uni-forms-item
          label="属性"
          name="attributes">
          <uni-easyinput
            v-model="plantData.attributes"
            placeholder="请输入属性" />
        </uni-forms-item>
        <uni-forms-item
          label="备注"
          name="note">
          <uni-easyinput
            type="textarea"
            :autoHeight="true"
            maxlength="200"
            v-model="plantData.note"
            placeholder="请输入备注" />
        </uni-forms-item>
      </uni-forms>
    </div>

    <div class="btn-container">
      <button
        type="primary"
        @click="submit('form')">
        提交
      </button>
      <button @click="cleanForm">取消</button>
    </div>
  </div>
</template>

<script>
import NavBar from "../../components/NavBar/NavBar.vue";
import { addPost } from "../../api/post.js";
import { mapState, mapMutations } from "vuex";
import { globalParams } from "../../../public/config.js";
import { addPlant, addKnowledgePlant, deletePlant } from "../../api/plant.js";

export default {
  computed: {
    ...mapState(["userInfo", "isPublished"]),
  },
  components: {
    NavBar,
  },
  data() {
    return {
      title: "",
      formData: {
        title: "",
        content: "",
      },
      plantData: {
        name: "",
        scientificName: "",
        overview: "",
        state: "",
        usage: "",
        attributes: "",
        note: "",
        imgUrl: "",
      },
      plantRules: {
        name: {
          rules: [
            {
              required: true,
              errorMessage: "请输入名称",
            },
          ],
        },

        scientificName: {
          rules: [
            {
              required: true,
              errorMessage: "请输入学名",
            },
          ],
        },

        overview: {
          rules: [
            {
              required: true,
              errorMessage: "请输入概览",
            },
          ],
        },
        state: {},
        usage: {},
        attributes: {},
        note: {},
      },
      fileList: [],
      imgData: {},
      rules: {
        title: {
          rules: [
            {
              required: true,
              errorMessage: "请输入标题",
            },
          ],
        },
        content: {
          rules: [
            {
              required: true,
              errorMessage: "请输入内容",
            },
          ],
        },
      },
      globalParams,
      pageType: "",
    };
  },
  onLoad(options) {
    this.pageType = options.type;
    this.title = options.title ? options.title : "发布";
  },
  methods: {
    ...mapMutations(["setIsPublished"]),
    // 返回上一页
    goBack() {
      uni.navigateBack({ delta: 1 });
    },
    async afterRead(event) {
      // 清空原数据
      this.fileList = [];
      console.log("vant上传图片", event);

      this.fileList.push({
        url: event.url,
      });
      console.log("fileList", this.fileList);
      if (this.fileList.length > 0) {
        uni.showLoading({
          title: "上传中",
          mask: false,
        });
        let { data: res } = await uni.uploadFile({
          url: globalParams.uploadUrl,
          filePath: this.fileList[0].url,
          name: "file",
          header: {
            "Content-Type": "multipart/form-data",
          },
        });
        let result = JSON.parse(res);

        if (result.code === 200) {
          uni.hideLoading();
          uni.showToast({
            title: "上传成功",
            icon: "none",
          });
          this.imgData = result.data;
          console.log("上传图片返回数据", this.imgData);
        } else {
          uni.hideLoading();
          uni.showToast({
            title: "上传失败",
            icon: "none",
          });
        }
      }
    },
    deleteFile() {
      this.fileList = [];
    },

    // 上传图片
    // uploadImage() {
    //   uni.chooseMedia({
    //     count: 1,
    //     mediaType: ["image"],
    //     sourceType: ["album", "camera"],
    //     sizeType: ["original"],
    //     maxDuration: 30,
    //     camera: "back",
    //     success(res) {
    //       console.log(res.tempFiles);
    //       this.previewImgUrl = res.tempFiles[0].tempFilePath;
    //       console.log("上传图片临时地址回显", this.previewImgUrl);
    //     },
    //   });
    // },
    // 表单提交
    submit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          console.log("success", res);
          if (this.fileList.length === 0) {
            uni.showToast({
              title: "请上传图片",
              icon: "none",
            });
          } else {
            this.publish();
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    // 清空表单
    cleanForm() {
      uni.navigateBack({ delta: 1 });
      this.formData = {
        title: "",
        content: "",
      };
    },

    // 发布
    async publish() {
      if (this.pageType === "community") {
        this._addPost();
      } else if (this.pageType === "knowledge") {
        this._addPlant();
      } else if (this.pageType === "record") {
      }
    },
    // 新增帖子
    async _addPost() {
      let { data: res } = await addPost({
        title: this.formData.title,
        content: this.formData.content,
        imgUrl: this.imgData.path,
        userId: this.userInfo.id,
      });
      console.log("发布帖子", res);
      if (res.code === 200) {
        uni.showToast({
          title: "发布成功",
          icon: "none",
        });
        this.setIsPublished(!this.isPublished);
        uni.navigateBack({ delta: 1 });
      }
    },
    // 新增植物
    async _addPlant() {
      let plantData = {
        name: this.plantData.name,
        scientificName: this.plantData.scientificName,
        overview: this.plantData.overview,
        state: this.plantData.state,
        usage: this.plantData.usage,
        attributes: this.plantData.attributes,
        note: this.plantData.note,
        imgUrl: this.imgData.path,
      };
      let { data: res } = await addPlant({ ...plantData });
      console.log("发布植物", res);
      // 植物新增成功后新增科普关联
      if (res.code === 200) {
        let { data: res2 } = await addKnowledgePlant({
          plantId: res.data.id,
          userId: this.userInfo.id,
        });
        if (res2.code === 200) {
          uni.showToast({
            title: "发布成功",
            icon: "none",
          });
          this.setIsPublished(!this.isPublished);
          uni.navigateBack({ delta: 1 });
        } else {
          // 植物新增成功，科普关联失败，删除植物
          let { data: res3 } = await deletePlant(res.data.id);
          console.log("删除植物", res3);
        }
      }
    },
    // 写入NFC
    writeNFCTag() {},
  },

  // 解决在微信小程序中 样式穿透无效的问题
  options: {
    styleIsolation: "shared",
  },
};
</script>

<style lang="scss" scoped>
.publish-page {
}
::v-deep .uni-forms {
  display: flex;
  .uni-forms-item {
    width: 90vw;
    .uni-forms-item__label {
      font-size: 16px;
      font-weight: 600;
      justify-content: flex-end !important;
      margin-right: 16px;
    }
  }
  .uni-easyinput__content {
    padding: 10px !important;
  }
  .is-input-border {
    border-radius: 12px;
    background-color: #f0f3fb;
  }
}
.upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  .add {
    width: 40px;
    height: 40px;
  }
  .previewPic {
    height: 188px;
  }
}
.btn-container {
  display: flex;
  flex-direction: column;
  gap: 16px;

  :first-child {
    background-color: #5282ff;
    color: #fff;
    width: 80vw;
    border-radius: 25px;
    font-size: 18px;
    font-weight: 700;
    line-height: 50px;
    height: 50px;

    &:active {
      background-color: #1b54d9;
      color: #ffffff;
    }
  }

  :last-child {
    width: 80vw;
    border-radius: 25px;
    font-size: 18px;
    font-weight: 700;
    line-height: 50px;
    height: 50px;
    background-color: #ffffff66;
    box-shadow: 0px 4px 16px 0px #edeef0;

    color: #2c3e50;
    &:active {
      background-color: #ffffff;
    }
  }
}
/* vant uploader 样式 */
::v-deep .van-uploader__upload {
  width: 80vw !important;
  height: 160px !important;
  margin: 0 !important;
  background-color: transparent;
}
::v-deep .van-uploader__preview-image {
  width: 80vw !important;
  height: 178px !important;
}
::v-deep .van-uploader__preview {
  margin: 0 !important;
}
</style>
